package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_LIST_KEY;

@Service
@Slf4j
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Override
    public Result follow(Long id, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String REDIS_FOLLOW_LIST_KEY = FOLLOW_LIST_KEY + userId;
        // 1. 判断是关注还是取关
        if (isFollow) {
            // 2. 关注，新增
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(id);
            boolean saveIsSuccess = save(follow);
            if (saveIsSuccess) {
                // redis 关注
                stringRedisTemplate.opsForSet().add(REDIS_FOLLOW_LIST_KEY, id.toString());
            }

        } else {
            // 3. 取关，删除
            boolean removeIsSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", id));
            if (removeIsSuccess) {
                // redis 取关
                stringRedisTemplate.opsForSet().remove(REDIS_FOLLOW_LIST_KEY, id.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long id) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 查询是否关注数，用 count 方便
        Integer count = query().eq("user_id", userId).eq("follow_user_id", id).count();
        return Result.ok(count > 0);
    }

    @Override
    public Result isCommon(Long id) {
        Long userId = UserHolder.getUser().getId();
        String NOW_USER_KEY = FOLLOW_LIST_KEY + userId;
        String COMMON_USER_KEY = FOLLOW_LIST_KEY + id;
        Set<String> intersect = stringRedisTemplate
                .opsForSet()
                .intersect(NOW_USER_KEY, COMMON_USER_KEY);
        // 解析 ID
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> collectId = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 根据 ID 查询
        List<UserDTO> userDTOS = userService.listByIds(collectId)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
